#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

const QString& SERVER_IP = "127.0.0.1";
const quint16 SERVER_PORT = 8080;

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("cf client");

    socket = new QUdpSocket(this);

    connect(socket, &QUdpSocket::readyRead,this,&Widget::proessResponse);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::proessResponse()
{
    QNetworkDatagram responseDatagram = socket->receiveDatagram();

    QString response = responseDatagram.data();

    ui->listWidget->addItem("服务器说: "+response);

}


void Widget::on_pushButton_clicked()
{
    const QString& text = ui->lineEdit->text();
    //构建Udp请求数据
    QNetworkDatagram requestDatagram(text.toUtf8(),QHostAddress(SERVER_IP),SERVER_PORT);

    socket->writeDatagram(requestDatagram);

    ui->listWidget->addItem("客户端说: " + text);

    ui->lineEdit->setText("");
}
